package com.android.delivery.util.permission;

import android.app.Activity;
import android.app.AppOpsManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import com.android.delivery.constant.ActivityRequestCode;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 悬浮窗权限工具类
 * @author liyu
 */
public class AlertPermissionUtil {

    /**
     * 判断 悬浮窗口权限是否打开
     * @param context
     * @return true 允许  false禁止
     */
    private static boolean checkWindowsPermission(Context context) {
        try {
            Object object = context.getSystemService(Context.APP_OPS_SERVICE);
            if (object == null) {
                return false;
            }
            Class localClass = object.getClass();
            Class[] arrayOfClass = new Class[3];
            arrayOfClass[0] = Integer.TYPE;
            arrayOfClass[1] = Integer.TYPE;
            arrayOfClass[2] = String.class;
            Method method = localClass.getMethod("checkOp", arrayOfClass);
            if (method == null) {
                return false;
            }
            Object[] arrayOfObject = new Object[3];
            arrayOfObject[0] = 24;
            arrayOfObject[1] = Binder.getCallingUid();
            arrayOfObject[2] = context.getPackageName();
            int m = ((Integer) method.invoke(object, arrayOfObject));
            return m == AppOpsManager.MODE_ALLOWED;
        } catch (Exception e) {
            Log.e(AlertPermissionUtil.class.getSimpleName(), e.getMessage());
        }
        return false;
    }

    /**
     * 判断 悬浮窗口权限是否打开
     * @param context
     * @return true 允许  false禁止
     */
    public static boolean checkAlertWindowsPermission(Context context) {
        if (Build.MANUFACTURER.equalsIgnoreCase("Meizu") && !checkWindowsPermission(context)){
            return false;
        }else if (Build.MANUFACTURER.equalsIgnoreCase("Xiaomi") && !checkWindowsPermission(context)){
            return false;
        }else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(context)) {
//                return false; //其他手机不需要悬浮窗权限
                return true;
            }else {
                return true;
            }
        }
    }

    //开启小米悬浮窗权限
    public static void requestXiaomiPermissions(Activity context) {
        try {
            Intent localIntent = new Intent(
                    "miui.intent.action.APP_PERM_EDITOR");
            localIntent.setClassName("com.miui.securitycenter",
                    "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            localIntent.putExtra("extra_pkgname", context.getPackageName());
            context.startActivityForResult(localIntent, ActivityRequestCode.LIVE_SYSTEM_ALERT_WINDOW_CODE);
        } catch (ActivityNotFoundException localActivityNotFoundException) {
            try {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                intent.setData(uri);
                context.startActivityForResult(intent, ActivityRequestCode.LIVE_SYSTEM_ALERT_WINDOW_CODE);
            }catch (Exception e){
                Log.e(AlertPermissionUtil.class.getSimpleName(), e.getMessage());
            }
        }
    }

    //开启魅族悬浮权限
    public static void requestMeizuPermissions(Activity context) {
        try {
            Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.putExtra("packageName", context.getPackageName());
            context.startActivityForResult(intent, ActivityRequestCode.LIVE_SYSTEM_ALERT_WINDOW_CODE);
        }catch (Exception e){
            Log.e(AlertPermissionUtil.class.getSimpleName(), e.getMessage());
        }
    }

    public static void requestPermissions(Activity context){
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        context.startActivityForResult(intent, ActivityRequestCode.LIVE_SYSTEM_ALERT_WINDOW_CODE);
    }

    public static boolean isNotificationEnabled(Context context) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                ApplicationInfo appInfo = context.getApplicationInfo();
                String pkg = context.getApplicationContext().getPackageName();
                int uid = appInfo.uid;
                Class appOpsClass = Class.forName(AppOpsManager.class.getName());
                Method checkOpNoThrowMethod = appOpsClass.getMethod("checkOpNoThrow", Integer.TYPE, Integer.TYPE,
                        String.class);
                Field opPostNotificationValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION");
                int value = (Integer) opPostNotificationValue.get(Integer.class);
                return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
            }
        } catch (ClassNotFoundException e) {
            Log.e(AlertPermissionUtil.class.getSimpleName(), e.getMessage());
        } catch (NoSuchMethodException e) {
            Log.e(AlertPermissionUtil.class.getSimpleName(), e.getMessage());
        } catch (NoSuchFieldException e) {
            Log.e(AlertPermissionUtil.class.getSimpleName(), e.getMessage());
        } catch (InvocationTargetException e) {
            Log.e(AlertPermissionUtil.class.getSimpleName(), e.getMessage());
        } catch (IllegalAccessException e) {
            Log.e(AlertPermissionUtil.class.getSimpleName(), e.getMessage());
        }
        return false;
    }
}
